package com.etcn.common.utils;

import java.text.DateFormat;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json工具类,将java对象转为json字符串或将json字符串转为java对象
 * @author guozc
 * @date 2015-12-09
 */
public class JsonHandler {
	private ObjectMapper objectMapper;
	
	private JsonHandler(Include inclusion){
		objectMapper = new ObjectMapper();
		objectMapper.setSerializationInclusion(inclusion);
		//设置时间格式,不能改
		DateFormat dateFormat = new SmartDateFormat();
		objectMapper.setDateFormat(dateFormat);
	}
	
	/**
	 * 构造转换对象
	 * @return JsonHandler
	 * @author guozc
	 * @date 2015-12-09
	 */ 
	public static JsonHandler build(){
		return new JsonHandler(Include.ALWAYS);
	}
	
	/**
	 * 构造转换对象,忽略为空的字段
	 * @return JsonHandler
	 * @author guozc
	 * @date 2015-12-09
	 */
	public static JsonHandler buildNoNull(){
		return new JsonHandler(Include.NON_NULL);
	}
	
	/**
	 * 构造转换对象,忽略为""的字段
	 * @return JsonHandler
	 * @author guozc
	 * @date 2015-12-09
	 */
	public static JsonHandler buildNoEmpty(){
		return new JsonHandler(Include.NON_EMPTY);
	}

	/**
	 * 将对象转为json字符串
	 * @param object 对象
	 * @return json格式字符串
	 * @author guozc
	 * @date 2015-12-09
	 */  
    public String toJson(Object object) throws Exception{
    	return objectMapper.writeValueAsString(object);  
    } 
	
    /**
     * json字符串转为简单类型对象
	 * @param jsonStr json字符串，valueType 转换对象Class
	 * @return 对象
	 * @author guozc
	 * @date 2015-12-09
	 */
    public <T> T toObject(String jsonStr, Class<T> valueType) throws Exception{  
    	return objectMapper.readValue(jsonStr, valueType);  
    } 
    
    /**
	 * json字符串转复杂类型对象
	 * @param jsonStr json字符串，type 类型构造器
	 * @return 对象
	 * @author guozc
	 * @date 2015-12-09
	 */
    public <T> T toObject(String jsonStr, TypeReference<T> type) throws Exception{  
           return objectMapper.readValue(jsonStr, type);  
    } 
    
    /**
     * 对象转复杂类型对象
     * @param obj 可转为json字符串的对象，valueType 转换对象Class
     * @return 对象
     * @author guozc
     * @date 2016-08-22
     */
    public <T> T Object2Object(Object obj,Class<T> valueType) throws Exception{
    	   return toObject(toJson(obj), valueType);
    }
    
}
